<template>
  <div class="detention-data-cards">
    <div class="cards-container">
      <div class="card-item"
           v-for="area in detentionData"
           :key="area.id"
           :class="{ updating: area.isUpdating }"
           @mouseenter="showTooltip($event, area)"
           @mouseleave="hideTooltip">
        <div class="card-content">
          <div class="card-header">
            <div class="area-name">{{ area.name }}</div>
            <div class="area-status" :class="area.status">
              <div class="status-dot"></div>
              <span>{{ area.statusText }}</span>
            </div>
          </div>
          <div class="card-body">
            <div class="metric-item">
              <div class="metric-label">使用率</div>
              <div class="metric-value usage-rate" :class="getUsageClass(area.displayUsageRate || area.usageRate)">
                {{ area.displayUsageRate || area.usageRate }}%
              </div>
            </div>
            <div class="progress-bar">
              <div class="progress-fill"
                   :style="{ width: (area.displayUsageRate || area.usageRate) + '%' }"
                   :class="getUsageClass(area.displayUsageRate || area.usageRate)"
                   :key="'fill-' + area.id + '-' + (area.displayUsageRate || area.usageRate)"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Tooltip -->
    <div v-if="tooltip.visible" class="detention-tooltip" :style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }">
      <div class="tooltip-header">
        <h4>{{ tooltip.data.name }}</h4>
      </div>
      <div class="tooltip-content">
        <div class="tooltip-row">
          <span class="tooltip-label">收押人数：</span>
          <span class="tooltip-value">{{ tooltip.data.detentionCount }}人</span>
        </div>
        <div class="tooltip-row">
          <span class="tooltip-label">总床位：</span>
          <span class="tooltip-value">{{ tooltip.data.totalBeds }}床</span>
        </div>
        <div class="tooltip-row">
          <span class="tooltip-label">使用率：</span>
          <span class="tooltip-value usage-rate" :class="getUsageClass(tooltip.data.usageRate)">
            {{ tooltip.data.usageRate }}%
          </span>
        </div>
        <div class="tooltip-row">
          <span class="tooltip-label">状态：</span>
          <span class="tooltip-value status-text" :class="tooltip.data.status">
            {{ tooltip.data.statusText }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DetentionDataCards',
  props: {
    analysisComplete: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      detentionData: [],
      tooltip: {
        visible: false,
        x: 0,
        y: 0,
        data: null
      }
    }
  },
  watch: {
    analysisComplete(newVal) {
      if (newVal) {
        this.startDynamicCardUpdate(newVal)
      }
    }
  },
  mounted() {
    this.generateMockData()
    // this.startDataUpdate()
  },
  beforeDestroy() {
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
    }
  },
  methods: {
    generateMockData() {
      this.detentionData = []

      for (let i = 1; i <= 11; i++) {
        // 生成基础数据
        const totalBeds = 80 + Math.floor(Math.random() * 40) // 80-120床位
        const usageRate = Math.floor(Math.random() * 100) // 0-100%使用率
        const detentionCount = Math.floor(totalBeds * usageRate / 100)

        // 根据使用率确定状态
        let status = 'normal'
        let statusText = '正常'
        if (usageRate >= 95) {
          status = 'full'
          statusText = '满员'
        } else if (usageRate >= 80) {
          status = 'high'
          statusText = '紧张'
        }

        this.detentionData.push({
          id: i,
          name: `第${i}监区`,
          detentionCount: detentionCount,
          totalBeds: totalBeds,
          usageRate: usageRate,
          status: status,
          statusText: statusText,
          isUpdating: false
        })
      }
    },

    getUsageClass(usageRate) {
      if (usageRate >= 95) return 'critical'
      if (usageRate >= 80) return 'high'
      if (usageRate >= 60) return 'medium'
      return 'low'
    },

    startDataUpdate() {
      this.updateTimer = setInterval(() => {
        this.updateData()
      }, 10000) // 每10秒更新一次
    },

    updateData() {
      // 先设置所有卡片为正在更新状态，触发动画
      const updatingData = this.detentionData.map(area => ({
        ...area,
        isUpdating: true
      }))
      this.detentionData = updatingData

      // 延迟一小段时间后更新实际数据
      setTimeout(() => {
        // 创建新数组以确保响应式更新 - 只进行增量增加
        const newData = this.detentionData.map(area => {
          // 增量增加：每次增加1-3人
          const increment = Math.floor(Math.random() * 3) + 1
          const newDetentionCount = Math.min(area.totalBeds, area.detentionCount + increment)
          const newUsageRate = Math.floor((newDetentionCount / area.totalBeds) * 100)

          // 重新计算状态
          let status = 'normal'
          let statusText = '正常'
          if (newUsageRate >= 95) {
            status = 'full'
            statusText = '满员'
          } else if (newUsageRate >= 80) {
            status = 'high'
            statusText = '紧张'
          }

          return {
            ...area,
            detentionCount: newDetentionCount,
            usageRate: newUsageRate,
            status,
            statusText,
            isUpdating: false // 动画结束后移除更新状态
          }
        })

        // 替换整个数组以触发响应式更新
        this.detentionData = newData
      }, 100) // 短暂延迟确保动画开始
    },

    showTooltip(event, areaData) {
      const rect = event.target.getBoundingClientRect()
      const containerRect = this.$el.getBoundingClientRect()

      // 计算tooltip位置，显示在鼠标右侧上方
      this.tooltip.x = rect.right - containerRect.left + 10
      this.tooltip.y = rect.top - containerRect.top - 10
      this.tooltip.data = areaData
      this.tooltip.visible = true
    },

    hideTooltip() {
      this.tooltip.visible = false
      this.tooltip.data = null
    },

    startDynamicCardUpdate(analysisData) {
      const { fileCount } = analysisData

      // 获取非满员的卡片索引（使用率<95%）
      const availableIndices = this.detentionData
        .map((area, index) => ({ area, index }))
        .filter(({ area }) => area.usageRate < 95)
        .map(({ index }) => index)

      if (availableIndices.length === 0) {
        console.log('没有可更新的卡片（所有卡片都已满员）')
        return
      }

      // 至少更新3个卡片，最多根据可用卡片数量和文件数量决定
      const maxUpdateCount = Math.min(availableIndices.length, fileCount, 5)
      const updateCount = Math.max(3, Math.min(maxUpdateCount, availableIndices.length))

      // 随机选择要更新的卡片
      const shuffledAvailableIndices = availableIndices
        .sort(() => Math.random() - 0.5)
        .slice(0, updateCount)

      console.log(`分析完成，将更新 ${updateCount} 个卡片（从 ${availableIndices.length} 个可用卡片中选择）`)

      // 为每个选中的卡片启动动态更新
      shuffledAvailableIndices.forEach((cardIndex, index) => {
        setTimeout(() => {
          this.dynamicUpdateCard(cardIndex)
        }, index * 300) // 每个卡片间隔300ms开始更新
      })
    },

    dynamicUpdateCard(cardIndex) {
      const card = this.detentionData[cardIndex]
      if (!card) return

      // 保存原始数据用于动画
      const originalCount = card.detentionCount
      const originalUsageRate = card.usageRate

      // 计算新的数据（增加3-8人，模拟分析结果）
      const increment = Math.floor(Math.random() * 6) + 3
      const newDetentionCount = Math.min(card.totalBeds, originalCount + increment)
      const newUsageRate = Math.floor((newDetentionCount / card.totalBeds) * 100)

      // 重新计算状态
      let status = 'normal'
      let statusText = '正常'
      if (newUsageRate >= 95) {
        status = 'full'
        statusText = '满员'
      } else if (newUsageRate >= 80) {
        status = 'high'
        statusText = '紧张'
      }

      // 创建新数组以触发响应式更新
      const newData = [...this.detentionData]
      newData[cardIndex] = {
        ...card,
        detentionCount: newDetentionCount,
        usageRate: newUsageRate,
        status,
        statusText,
        isUpdating: true,
        originalCount, // 保存原始数据用于动画
        originalUsageRate
      }

      this.detentionData = newData

      // 启动数字滚动动画
      this.startNumberAnimation(cardIndex, originalCount, newDetentionCount, originalUsageRate, newUsageRate)

      // 2秒后移除更新状态
      setTimeout(() => {
        const finalData = [...this.detentionData]
        finalData[cardIndex] = {
          ...finalData[cardIndex],
          isUpdating: false,
          originalCount: undefined,
          originalUsageRate: undefined
        }
        this.detentionData = finalData
      }, 2500)
    },

    startNumberAnimation(cardIndex, fromCount, toCount, fromUsage, toUsage) {
      const card = this.detentionData[cardIndex]
      if (!card) return

      const duration = 1500 // 1.5秒动画
      const steps = 60 // 60帧
      const stepDuration = duration / steps

      let currentStep = 0
      const countIncrement = (toCount - fromCount) / steps
      const usageIncrement = (toUsage - fromUsage) / steps

      const animate = () => {
        currentStep++
        const progress = currentStep / steps

        if (currentStep <= steps) {
          const currentCount = Math.round(fromCount + countIncrement * currentStep)
          const currentUsage = Math.round((fromUsage + usageIncrement * currentStep) * 10) / 10

          // 更新当前显示的数值（用于动画显示）
          const newData = [...this.detentionData]
          newData[cardIndex] = {
            ...newData[cardIndex],
            displayCount: currentCount,
            displayUsageRate: currentUsage
          }
          this.detentionData = newData

          setTimeout(animate, stepDuration)
        }
      }

      animate()
    }
  }
}
</script>

<style scoped>
.detention-data-cards {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px;
  overflow: hidden;
}

.cards-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-shrink: 0;
}

.cards-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(45deg,
    rgba(0, 120, 160, 0.9) 0%,
    rgba(0, 100, 140, 0.8) 50%,
    rgba(0, 80, 120, 0.7) 100%
  );
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 0 10px rgba(0, 100, 150, 0.4);
}

.cards-container {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 4px;
  overflow: hidden;
  padding: 3px;
}

.card-item {
  height: 100%;
  background:
    linear-gradient(145deg,
      rgba(0, 80, 120, 0.15) 0%,
      rgba(0, 100, 140, 0.1) 50%,
      rgba(0, 60, 100, 0.08) 100%
    ),
    radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.06) 0%, transparent 70%),
    rgba(0, 0, 0, 0.4);
  border-radius: 8px;
  border: 1px solid rgba(0, 100, 150, 0.3);
  backdrop-filter: blur(8px);
  box-shadow:
    0 4px 20px rgba(0, 100, 150, 0.15),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  transition: all 0.3s cubic-bezier(0.23, 1, 0.32, 1);
  cursor: pointer;
}

.card-item.updating {
  animation: cardFlash 2.5s ease-in-out, cardPulse 0.8s ease-in-out infinite alternate;
  transform: scale(1.05);
  z-index: 10;
}

.card-item:hover {
  transform: translateY(-2px);
  border-color: rgba(0, 100, 150, 0.5);
  box-shadow:
    0 8px 30px rgba(0, 100, 150, 0.25),
    inset 0 1px 0 rgba(255, 255, 255, 0.15);
}

.card-content {
  padding: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.area-name {
  font-size: 12px;
  font-weight: bold;
  color: #00ffff;
  text-shadow: 0 0 6px rgba(0, 255, 255, 0.4);
}

.area-status {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 10px;
  font-weight: 500;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #00ff88;
}

.area-status.normal .status-dot {
  background: #00ff88;
}

.area-status.high .status-dot {
  background: #ffa500;
}

.area-status.full .status-dot {
  background: #ff4444;
}

.card-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.metric-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metric-label {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.7);
}

.metric-value {
  font-size: 11px;
  font-weight: bold;
  color: #00ffff;
  text-shadow: 0 0 4px rgba(0, 255, 255, 0.3);
}

.usage-rate.critical {
  color: #ff4444;
  text-shadow: 0 0 6px rgba(255, 68, 68, 0.5);
}

.usage-rate.high {
  color: #ffa500;
  text-shadow: 0 0 6px rgba(255, 165, 0, 0.5);
}

.usage-rate.medium {
  color: #ffff00;
  text-shadow: 0 0 6px rgba(255, 255, 0, 0.5);
}

.usage-rate.low {
  color: #00ff88;
  text-shadow: 0 0 6px rgba(0, 255, 136, 0.5);
}

.progress-bar {
  width: 100%;
  height: 3px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 1px;
  overflow: hidden;
  margin-top: 4px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #00ffff, #0080ff);
  border-radius: 1px;
  transition: width 1.5s cubic-bezier(0.4, 0, 0.2, 1), background 0.8s ease;
  transform-origin: left;
}

.progress-fill.critical {
  background: linear-gradient(90deg, #ff4444, #ff0000);
}

.progress-fill.high {
  background: linear-gradient(90deg, #ffa500, #ff6600);
}

.progress-fill.medium {
  background: linear-gradient(90deg, #ffff00, #ffaa00);
}

.progress-fill.low {
  background: linear-gradient(90deg, #00ff88, #00cc66);
}

@keyframes cardFlash {
  0% {
    box-shadow:
      0 4px 20px rgba(0, 100, 150, 0.15),
      inset 0 1px 0 rgba(255, 255, 255, 0.1);
  }
  25% {
    box-shadow:
      0 4px 20px rgba(0, 100, 150, 0.15),
      inset 0 1px 0 rgba(255, 255, 255, 0.1),
      0 0 20px rgba(255, 165, 0, 0.4);
  }
  50% {
    box-shadow:
      0 4px 20px rgba(0, 100, 150, 0.15),
      inset 0 1px 0 rgba(255, 255, 255, 0.1),
      0 0 30px rgba(255, 165, 0, 0.6),
      0 0 40px rgba(255, 165, 0, 0.3),
      0 0 60px rgba(255, 165, 0, 0.2);
  }
  75% {
    box-shadow:
      0 4px 20px rgba(0, 100, 150, 0.15),
      inset 0 1px 0 rgba(255, 255, 255, 0.1),
      0 0 20px rgba(255, 165, 0, 0.4);
  }
  100% {
    box-shadow:
      0 4px 20px rgba(0, 100, 150, 0.15),
      inset 0 1px 0 rgba(255, 255, 255, 0.1);
  }
}

@keyframes cardPulse {
  0% {
    transform: scale(1.05);
    filter: brightness(1);
  }
  100% {
    transform: scale(1.08);
    filter: brightness(1.2) saturate(1.3);
  }
}

/* Tooltip样式 */
.detention-tooltip {
  position: absolute;
  background:
    linear-gradient(145deg,
      rgba(0, 20, 40, 0.95) 0%,
      rgba(0, 30, 60, 0.9) 50%,
      rgba(0, 15, 35, 0.95) 100%
    ),
    radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.1) 0%, transparent 70%),
    rgba(0, 0, 0, 0.8);
  border: 1px solid rgba(0, 100, 150, 0.5);
  border-radius: 8px;
  padding: 0;
  box-shadow:
    0 8px 32px rgba(0, 100, 150, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1),
    0 0 20px rgba(0, 255, 255, 0.1);
  backdrop-filter: blur(12px);
  z-index: 1000;
  pointer-events: none;
  min-width: 180px;
  max-width: 220px;
  animation: tooltipFadeIn 0.2s ease-out;
}

.tooltip-header {
  padding: 10px 12px 8px;
  border-bottom: 1px solid rgba(0, 100, 150, 0.3);
  margin-bottom: 0;
}

.tooltip-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #00ffff;
  text-shadow: 0 0 8px rgba(0, 255, 255, 0.5);
}

.tooltip-content {
  padding: 8px 12px 10px;
}

.tooltip-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-size: 12px;
}

.tooltip-row:last-child {
  margin-bottom: 0;
}

.tooltip-label {
  color: rgba(255, 255, 255, 0.7);
  font-weight: 500;
}

.tooltip-value {
  font-weight: 600;
  color: #ffffff;
  text-shadow: 0 0 4px rgba(255, 255, 255, 0.3);
}

.tooltip-value.usage-rate.critical {
  color: #ff4444;
  text-shadow: 0 0 6px rgba(255, 68, 68, 0.6);
}

.tooltip-value.usage-rate.high {
  color: #ffa500;
  text-shadow: 0 0 6px rgba(255, 165, 0, 0.6);
}

.tooltip-value.usage-rate.medium {
  color: #ffff00;
  text-shadow: 0 0 6px rgba(255, 255, 0, 0.6);
}

.tooltip-value.usage-rate.low {
  color: #00ff88;
  text-shadow: 0 0 6px rgba(0, 255, 136, 0.6);
}

.tooltip-value.status-text.normal {
  color: #00ff88;
  text-shadow: 0 0 6px rgba(0, 255, 136, 0.6);
}

.tooltip-value.status-text.high {
  color: #ffa500;
  text-shadow: 0 0 6px rgba(255, 165, 0, 0.6);
}

.tooltip-value.status-text.full {
  color: #ff4444;
  text-shadow: 0 0 6px rgba(255, 68, 68, 0.6);
}

@keyframes tooltipFadeIn {
  0% {
    opacity: 0;
    transform: translateY(5px) scale(0.95);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .detention-tooltip {
    min-width: 160px;
    max-width: 200px;
  }

  .tooltip-header h4 {
    font-size: 13px;
  }

  .tooltip-row {
    font-size: 11px;
  }
}

</style>
